package com.campusify.service.impl;

import org.springframework.stereotype.Service;
import com.campusify.compents.PageResult;
import com.campusify.pojo.PostsExample;
import com.campusify.pojo.PostsExample.Criteria;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.campusify.mapper.PostsMapper;
import com.campusify.pojo.Posts;
import com.campusify.service.PostsService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 服务实现层
 * @author Administrator
 *
 */
@Service
public class PostsServiceImpl implements PostsService {

	@Autowired
	private PostsMapper postsMapper;
	
	/**
	 * 查询全部
	 */
	@Override
	public List<Posts> findAll() {
		return postsMapper.selectByExample(null);
	}

	/**
	 * 按分页查询
	 */
	@Override
	public PageResult findPage(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);		
		Page<Posts> page=   (Page<Posts>) postsMapper.selectByExample(null);
		return new PageResult(page.getTotal(), page.getResult());
	}

	/**
	 * 增加
	 */
	@Override
	public void add(Posts posts) {
		postsMapper.insert(posts);		
	}

	
	/**
	 * 修改
	 */
	@Override
	public void update(Posts posts){
		postsMapper.updateByPrimaryKey(posts);
	}	
	
	/**
	 * 根据ID获取实体
	 * @param id
	 * @return
	 */
	@Override
	public Posts findOne(Integer postID){
		return postsMapper.selectByPrimaryKey(postID);
	}

	/**
	 * 批量删除
	 */
	@Override
	public void delete(Integer[] postIDs) {
		for(Integer postID:postIDs){
			postsMapper.deleteByPrimaryKey(postID);
		}		
	}
	
	
		@Override
	public PageResult findPage(Posts posts, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		
		PostsExample example=new PostsExample();
		Criteria criteria = example.createCriteria();
		
		if(posts!=null){			
						if(posts.getTitle()!=null && posts.getTitle().length()>0){
				criteria.andTitleLike("%"+posts.getTitle()+"%");
			}			if(posts.getContent()!=null && posts.getContent().length()>0){
				criteria.andContentLike("%"+posts.getContent()+"%");
			}			if(posts.getPublishtime()!=null && posts.getPublishtime().length()>0){
				criteria.andPublishtimeLike("%"+posts.getPublishtime()+"%");
			}			if(posts.getImgs()!=null && posts.getImgs().length()>0){
				criteria.andImgsLike("%"+posts.getImgs()+"%");
			}	
		}
		
		Page<Posts> page= (Page<Posts>)postsMapper.selectByExample(example);		
		return new PageResult(page.getTotal(), page.getResult());
	}
	
}
